package com.atguigu.cloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class RateLimitController {

    @GetMapping("/rateLimit/byUrl")
    public String byUrl()
    {
        return "按rest地址限流测试OK";
    }

    @GetMapping("/rateLimit/byResource")
    @SentinelResource(value = "byResource", blockHandler = "handleException",fallback = "byResourceFallback")
    public String byResource()
    {
        int u =10/0;
        return "按rest地址限流测试OK";
    }

    public String handleException(BlockException throwable){
        // 自定义限流返回
        log.error("系统繁忙，请稍后再试",throwable);
        return "触发了blockHandler";
    }

    public String byResourceFallback(Throwable throwable){
        // jvm报错后，会进入fallback方法
        log.error("系统繁忙，请稍后再试",throwable);
        return "系统繁忙，请稍后再试";
    }

    @GetMapping("/testHotKey")
    @SentinelResource(value = "testHotKey",blockHandler = "dealHandler_testHotKey")
    public String testHotKey(@RequestParam(value = "p1",required = false) String p1,
                             @RequestParam(value = "p2",required = false) String p2){
        return "------testHotKey";
    }
    public String dealHandler_testHotKey(String p1,String p2,BlockException exception)
    {
        return "-----dealHandler_testHotKey";
    }
}
